import axios from "axios";

import { useCommonStore } from "@/stores";
import { nextTick } from "vue";

let  commonStore = null;
nextTick(()=>{
  commonStore = useCommonStore();
})

const baseURL = import.meta.env.VITE_WEB_BASE_API;

console.log(baseURL);

const http = axios.create({
  baseURL,
  timeout: 8000,//超时时间  0代表永不超时
});

http.interceptors.request.use(
  async (config) => {
    const token = commonStore.getToken;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


http.interceptors.response.use(
  (response) => {
    if (response.data.code === 'token 过期') {//token过期
      return Promise.reject(new Error(response.data.message));
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);


export const postapi = (url, params={},headers={'Content-Type': 'application/json; charset=utf-8'}) => {
  return new Promise((resolve, reject) => {
    http({
      url,
      method:'post',
      data: params,
      headers,
    })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}  

export const getapi = (url, params={},headers={'Content-Type': 'application/json; charset=utf-8'}) => {
  return new Promise((resolve, reject) => {
    http({
      url,
      method:'get',
      params: params,
      headers,
    })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}  

